package com.cloudinnov.controller.api;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cloudinnov.aop.SystemLog;
import com.cloudinnov.logic.BxManagerLogic;
import com.cloudinnov.logic.ControlSolutionSendRecordItemLogic;
import com.cloudinnov.logic.EquipmentsAttrLogic;
import com.cloudinnov.logic.EquipmentsLogic;
import com.cloudinnov.model.ControlSolutionSendRecordItem;
import com.cloudinnov.model.Equipments;
import com.cloudinnov.model.EquipmentsAttr;
import com.cloudinnov.model.PageModel;
import com.cloudinnov.model.TreeObject;
import com.cloudinnov.utils.CommonUtils;
import com.cloudinnov.utils.model.BxClientModel;
import com.github.pagehelper.Page;

/**
 * 情报板控制
 * @ClassName: BxManagerController
 * @Description:
 * @author: ningmeng
 * @date: 2016年11月30日 下午2:23:32
 */
@Controller
@RequestMapping("/webapi/bxManager")
public class BxManagerController extends BaseController {
    public final Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private EquipmentsAttrLogic equipmentsAttrLogic;
    @Autowired
    private BxManagerLogic bxManagerLogic;
    @Autowired
    private EquipmentsLogic equipmentsLogic;
    @Autowired
    private ControlSolutionSendRecordItemLogic controlSolutionSendRecordItemLogic;

    @RequestMapping(value = "/sendText", method = RequestMethod.POST)
    @ResponseBody
    public void sendText(HttpServletRequest request, HttpServletResponse response, EquipmentsAttr model, String text)
            throws IOException {
        String returnData = "";
        Map<String, Object> map = new HashMap<String, Object>();
        List<EquipmentsAttr> configList = equipmentsAttrLogic.selectList(model, false);
        if (configList != null && configList.size() > 0) {
            BxClientModel bxModel = new BxClientModel();
            for (EquipmentsAttr attr : configList) {
                if (attr.getCustomTag() != null) {
                    if (attr.getCustomTag().equals(BxClientModel.IP)) {
                        bxModel.setIp(attr.getValue());
                    } else if (attr.getCustomTag().equals(BxClientModel.PORT)) {
                        bxModel.setPort(Integer.parseInt(attr.getValue()));
                    } else if (attr.getCustomTag().equals(BxClientModel.WIDHT)) {
                        bxModel.setWidth(Integer.parseInt(attr.getValue()));
                    } else if (attr.getCustomTag().equals(BxClientModel.HEIGHT)) {
                        bxModel.setHeight(Integer.parseInt(attr.getValue()));
                    }
                }
            }
            bxModel.setText(text);
            if (bxModel.getIp() != null && bxModel.getPort() != 0) {
                try {
                    int returnCode = bxManagerLogic.sendTextBoardSanSi(bxModel, model.getEquipmentCode());
                    if (returnCode == CommonUtils.SUCCESS_NUM) {
                        returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
                    } else {
                        returnData = returnJsonAllRequest(request, response, map, ERROR, "");
                    }
                } catch (Exception e) {
                    map.put("data", e);
                    returnData = returnJsonAllRequest(request, response, map, ERROR, "");
                }
            } else {
                map.put("data", "情报板参数未设置!");
                returnData = returnJsonAllRequest(request, response, map, CommonUtils.PARAMETER_EXCEPTION_CODE, "");
            }
        } else {
            returnData = returnJsonAllRequest(request, response, map, ERROR, "");
        }
        response.getWriter().println(returnData);
    }
    @RequestMapping(value = "/sendTexts", method = RequestMethod.POST)
    @ResponseBody
    public void sendTexts(HttpServletRequest request, HttpServletResponse response, EquipmentsAttr model,
            BxClientModel bxModel) throws IOException {
        String returnData = "";
        Map<String, Object> map = new HashMap<String, Object>();
        if (model.getEquipmentCode() != null) {
            int returnCode = 0;
            String[] equipmentCodes = model.getEquipmentCode().split(",");
            for (String equipmentCode : equipmentCodes) {
                model = new EquipmentsAttr();
                model.setEquipmentCode(equipmentCode);
                List<EquipmentsAttr> configList = equipmentsAttrLogic.selectList(model, false);
                if (configList != null && configList.size() > 0) {
                    for (EquipmentsAttr attr : configList) {
                        if (attr.getCustomTag() != null) {
                            if (attr.getCustomTag().equals(BxClientModel.IP)) {
                                bxModel.setIp(attr.getValue() != null ? attr.getValue() : "0");
                            } else if (attr.getCustomTag().equals(BxClientModel.PORT)) {
                                bxModel.setPort(Integer.parseInt(attr.getValue() != null ? attr.getValue() : "0"));
                            } else if (attr.getCustomTag().equals(BxClientModel.WIDHT)) {
                                bxModel.setWidth(Integer.parseInt(attr.getValue()));
                            } else if (attr.getCustomTag().equals(BxClientModel.HEIGHT)) {
                                bxModel.setHeight(Integer.parseInt(attr.getValue()));
                            }
                        }
                    }
                    if (bxModel.getIp() != null && bxModel.getPort() != 0) {
                        try {
                            Equipments equipment = new Equipments();
                            equipment.setCode(equipmentCode);
                            equipment = equipmentsLogic.selectEquipmentsByCode(equipment);
                            
                            bxModel.setLoginName(getUserInfo(request).get(LOGIN_NAME));
                            if(equipment !=null && equipment.getCategoryCode().equals("DHQBBKBQBB")) {//大华情报板
                                returnCode = bxManagerLogic.sendTextsBoardNovaStar(bxModel, model.getEquipmentCode());
                            }else {
                                returnCode = bxManagerLogic.sendTextsBoardSanSi(bxModel, model.getEquipmentCode());
                            }
                            
                            if (returnCode == CommonUtils.SUCCESS_NUM) {
                                returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
                            } else {
                                returnData = returnJsonAllRequest(request, response, map, ERROR, "");
                            }
                        } catch (Exception e) {
                            map.put("data", e);
                            returnCode = CommonUtils.ERROR_NUM;
                        }
                    } else {
                        map.put("data", "情报板参数未设置!");
                        returnCode = CommonUtils.ERROR_NUM;
                    }
                } else {
                    returnCode = CommonUtils.ERROR_NUM;
                }
            }
            if (returnCode == CommonUtils.SUCCESS_NUM) {
                returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
            } else {
                returnData = returnJsonAllRequest(request, response, map, ERROR, "");
            }
        } else {
        }
        response.getWriter().println(returnData);
    }
    
    @RequestMapping(value = "/infoBoardStatus", method = RequestMethod.GET)
    @ResponseBody
    public void cameraStatus(HttpServletRequest request, HttpServletResponse response, EquipmentsAttr model)
            throws IOException {
        String returnData = "";
        Map<String, Object> map = new HashMap<String, Object>();
        List<EquipmentsAttr> configList = equipmentsAttrLogic.selectList(model, false);
        if (configList != null && configList.size() > 0) {
            BxClientModel bxModel = new BxClientModel();
            for (EquipmentsAttr attr : configList) {
                if (attr.getCustomTag() != null) {
                    if (attr.getCustomTag().equals(BxClientModel.IP)) {
                        bxModel.setIp(attr.getValue());
                    } else if (attr.getCustomTag().equals(BxClientModel.PORT)) {
                        bxModel.setPort(Integer.parseInt(attr.getValue()));
                    } else if (attr.getCustomTag().equals(BxClientModel.WIDHT)) {
                        bxModel.setWidth(Integer.parseInt(attr.getValue()));
                    } else if (attr.getCustomTag().equals(BxClientModel.HEIGHT)) {
                        bxModel.setHeight(Integer.parseInt(attr.getValue()));
                    }
                }
            }
            if (bxModel.getIp() != null && bxModel.getPort() != 0) {
                try {
                    if (bxManagerLogic.selectInfoBoardStatus(bxModel)) {
                        returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
                    } else {
                        returnData = returnJsonAllRequest(request, response, map, ERROR, "");
                    }
                } catch (Exception e) {
                    map.put("data", e);
                    returnData = returnJsonAllRequest(request, response, map, CommonUtils.SYSTEM_EXCEPTION_CODE, "");
                }
            } else {
                map.put("data", "设备情报板参数未设置!");
                returnData = returnJsonAllRequest(request, response, map, CommonUtils.PARAMETER_EXCEPTION_CODE, "");
            }
        } else {
            returnData = returnJsonAllRequest(request, response, map, ERROR, "");
        }
        response.getWriter().println(returnData);
    }
    
    @RequestMapping(value = "/boardPreview", method = RequestMethod.GET)
    @ResponseBody
    public void selectBoardPreview(HttpServletRequest request, HttpServletResponse response, EquipmentsAttr model)
            throws IOException {
        String returnData = "";
        Map<String, Object> map = new HashMap<String, Object>();
        List<EquipmentsAttr> configList = equipmentsAttrLogic.selectList(model, false);
        if (configList != null && configList.size() > 0) {
            BxClientModel bxModel = new BxClientModel();
            for (EquipmentsAttr attr : configList) {
                if (attr.getCustomTag() != null) {
                    if (attr.getCustomTag().equals(BxClientModel.IP)) {
                        bxModel.setIp(attr.getValue());
                    } else if (attr.getCustomTag().equals(BxClientModel.PORT)) {
                        bxModel.setPort(Integer.parseInt(attr.getValue()));
                    } else if (attr.getCustomTag().equals(BxClientModel.WIDHT)) {
                        bxModel.setWidth(Integer.parseInt(attr.getValue()));
                    } else if (attr.getCustomTag().equals(BxClientModel.HEIGHT)) {
                        bxModel.setHeight(Integer.parseInt(attr.getValue()));
                    }
                }
            }
            if (bxModel.getIp() != null && bxModel.getPort() != 0) {
                try {
                    Equipments equipment = new Equipments();
                    equipment.setCode(model.getEquipmentCode());
                    equipment = equipmentsLogic.selectEquipmentsByCode(equipment);
                    bxModel.setLoginName(getUserInfo(request).get(LOGIN_NAME));
                    if(equipment !=null && equipment.getCategoryCode().equals("DHQBBKBQBB")) {//大华情报板
                        map = bxManagerLogic.selectBoardSanNova(model.getEquipmentCode());
                    }else {
                        map = bxManagerLogic.selectBoardSanSiText(model.getEquipmentCode());
                    }
                    returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
                } catch (Exception e) {
                    map.put("data", e);
                    returnData = returnJsonAllRequest(request, response, map, CommonUtils.SYSTEM_EXCEPTION_CODE, "");
                }
            } else {
                map.put("data", "设备情报板参数未设置!");
                returnData = returnJsonAllRequest(request, response, map, CommonUtils.PARAMETER_EXCEPTION_CODE, "");
            }
        } else {
            returnData = returnJsonAllRequest(request, response, map, ERROR, "");
        }
        response.getWriter().println(returnData);
    }
    
    /**
     * 强制触发触发器 forcedToInforBorad
     * @Description
     * @param
     * @return
     */
    @RequestMapping(value = "/forcedToInforBorad", method = RequestMethod.POST)
    @ResponseBody
    @SystemLog(module = "情报板管理", methods = "强制触发触发器")
    public void forcedToInforBorad(String code, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        int result = bxManagerLogic.forcedToInforBorad(code);
        String returnData = "";
        HashMap<String, Object> map = new HashMap<String, Object>();
        if (result == 1) {
            returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
        } else {
            returnData = returnJsonAllRequest(request, response, map, ERROR, "");
        }
        response.getWriter().print(returnData);
    }
    
    /**
     * 查询设备分类以及设备分类下的设备
     * @param equipments
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "selectEquiClassifyAndEquipments", method = RequestMethod.GET)
    @ResponseBody
    @SystemLog(module = "大屏管理", methods = "查询设备分类以及设备分类下的设备")
    public void selectEquiClassifyAndEquipments(Equipments equipments, HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        List<Equipments> listInfo = equipmentsLogic.selectEquiClassifyAndEquipments(equipments);
        String returnData = "";
        HashMap<String, Object> map = new HashMap<String, Object>();
        if (listInfo.size() != 0) {
            map.put("list", listInfo);
            returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
        } else {
            returnData = returnJsonAllRequest(request, response, map, ERROR, "");
        }
        response.getWriter().println(returnData);
    }
    
    /**
     * 设备分类树与设备树
     * @param equipments
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/selectEquiClassifyAndTreeEquipmentsTree", method = RequestMethod.GET)
    @ResponseBody
    @SystemLog(module = "大屏管理", methods = "设备分类树与设备树")
    public void selectEquiClassifyAndTreeEquipmentsTree(Equipments equipments, HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        List<Equipments> listInfo = equipmentsLogic.selectEquiClassifyTreeAndEquipmentsTree(equipments);
        String returnData = "";
        HashMap<String, Object> map = new HashMap<String, Object>();
        if (listInfo.size() != 0) {
            List<TreeObject> list = new ArrayList<TreeObject>();
            TreeObject treeModel = null;
            for (int i = 0; i < listInfo.size(); i++) {
                treeModel = new TreeObject();
                treeModel.setId(listInfo.get(i).getCode());
                treeModel.setIndexId(listInfo.get(i).getId());
                treeModel.setParentId(listInfo.get(i).getParentId());
                treeModel.setSelectId(listInfo.get(i).getId());
                treeModel.setCode(listInfo.get(i).getCode());
                treeModel.setName(listInfo.get(i).getName());
                treeModel.setText(listInfo.get(i).getName());
                treeModel.setComment(listInfo.get(i).getComment());
                treeModel.setGrade(0);
                treeModel.setChildren(listInfo.get(i).getChildren());
                list.add(treeModel);
            }
            map.put("list", list);
            returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
        } else {
            returnData = returnJsonAllRequest(request, response, map, ERROR, "");
        }
        response.getWriter().println(returnData);
    }
    @RequestMapping(value = "/getTemplate", method = RequestMethod.GET)
    @ResponseBody
    public void selectTemplate(HttpServletRequest request, HttpServletResponse response, String equipmentCode)
            throws IOException {
        String returnData = "";
        Map<String, Object> map = new HashMap<String, Object>();
        EquipmentsAttr model = new EquipmentsAttr();
        model.setEquipmentCode(equipmentCode);
        List<EquipmentsAttr> configList = equipmentsAttrLogic.selectList(model, false);
        if (configList != null && configList.size() > 0) {
            for (EquipmentsAttr attr : configList) {
                if (attr.getCustomTag() != null) {
                    if (attr.getCustomTag().equals(BxClientModel.WIDHT)) {
                        map.put("width", Integer.parseInt(attr.getValue()));
                    } else if (attr.getCustomTag().equals(BxClientModel.HEIGHT)) {
                        map.put("height", Integer.parseInt(attr.getValue()));
                    }
                }
            }
        }
        List<Map<String, Object>> data = bxManagerLogic.selectTemplateByCateCode(equipmentCode);// 查询情报板方案模板
        List<Map<String, Object>> lastSendLogs = bxManagerLogic.selectLastSendRecordByEquipmentCode(equipmentCode);// 查询此设备最后发送记录(模板)
        List<Map<String, Object>> sendLogs = bxManagerLogic.selectSendRecordByEquipmentCode(equipmentCode, 1);// 查询此设备最后发送记录(模板)
        map.put("list", data);
        map.put("lastSendLogs", lastSendLogs);
        map.put("sendLogs", sendLogs);
        returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
        response.getWriter().println(returnData);
    }
    @RequestMapping(value = "/getText", method = RequestMethod.GET)
    @ResponseBody
    public void getText(HttpServletRequest request, HttpServletResponse response, String equipmentCode)
            throws IOException {
        String returnData = "";
        Map<String, Object> map = bxManagerLogic.selectBoardSanSiText(equipmentCode);
        returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
        response.getWriter().println(returnData);
    }
    /**
     * 根据设备名称查询设备
     * @param equipments
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/selectEquipmentsByName", method = RequestMethod.POST)
    @ResponseBody
    @SystemLog(module = "大屏管理", methods = "根据设备名称查询设备")
    public void selectEquipmentsByName(Equipments equipments, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        List<Equipments> equipmentsinfo = equipmentsLogic.selectEquipmentsByName(equipments);
        String returnData = "";
        HashMap<String, Object> map = new HashMap<String, Object>();
        if (equipmentsinfo.size() > 0) {
            map.put("list", equipmentsinfo);
            returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
        } else {
            returnData = returnJsonAllRequest(request, response, map, ERROR, "");
        }
        response.getWriter().print(returnData);
    }
    /**
     * 根据设备code查询设备
     * @param equipments
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/selectEquipmentsByCode", method = RequestMethod.GET)
    @ResponseBody
    @SystemLog(module = "大屏管理", methods = "根据设备code查询设备")
    public void selectEquipmentsByCode(Equipments equipments, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        Equipments equipInfo = equipmentsLogic.selectEquipmentsByCode(equipments);
        String returnData = "";
        HashMap<String, Object> map = new HashMap<String, Object>();
        if (equipInfo != null) {
            map.put("model", equipInfo);
            returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
        } else {
            returnData = returnJsonAllRequest(request, response, map, ERROR, "");
        }
        response.getWriter().print(returnData);
    }
    @RequestMapping(value = "/deleteSendLog", method = RequestMethod.POST)
    @SystemLog(module = "情报板管理", methods = "删除发送记录")
    public void deleteSendLog(ControlSolutionSendRecordItem model, HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        model.setCode(model.getCode().split("-")[0]);
        int returnCode = bxManagerLogic.deleteSendRecordLog(model);
        String returnData = "";
        Map<String, Object> map = new HashMap<String, Object>();
        if (returnCode == SUCCESS) {
            returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
        } else {
            returnData = returnJsonAllRequest(request, response, map, ERROR, "");
        }
        response.getWriter().print(returnData);
    }
    @RequestMapping(value = "/report/list", method = RequestMethod.GET)
    public void reportList(@Valid PageModel page, BindingResult error, HttpServletRequest request,
            HttpServletResponse response, ControlSolutionSendRecordItem model, String startTime, String endTime,
            String sectionCode) throws IOException {
        // 校验没有通过
        if (error.hasErrors()) {
            getErrors(error);
            return;
        }
        String returnData = "";
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sectionCode", sectionCode);
        params.put("cateCode", model.getCateCode());
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        Page<ControlSolutionSendRecordItem> list = controlSolutionSendRecordItemLogic.search(page, params);
        if (list != null) {
            map.put("list", list);
            map.put("total", list.getTotal());
        }
        returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
        response.getWriter().println(returnData);
    }
    @RequestMapping(value = "/report/detail", method = RequestMethod.GET)
    public void reportDetail(HttpServletRequest request, HttpServletResponse response,
            ControlSolutionSendRecordItem model) throws IOException {
        String returnData = "";
        Map<String, Object> map = new HashMap<String, Object>();
        ControlSolutionSendRecordItem result = controlSolutionSendRecordItemLogic
                .selectListByEquCodeAndSendTime(model.getEquipmentCode(), model.getSendTime());
        if (result != null) {
            map.put("model", result);
        }
        returnData = returnJsonAllRequest(request, response, map, SUCCESS, "");
        response.getWriter().println(returnData);
    }
}
